package controllers;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Set;

import event.EventHandler;

import models.Establishment;
import models.FoodCourt;
import models.MenuItem;
import models.MenuSection;
import models.Order;
import models.Picture;
import models.Place;
import models.User;
import play.cache.Cache;
import play.mvc.Controller;
import play.mvc.Scope;
import play.mvc.WebSocketController;
import play.mvc.With;
import util.FileUtil;

@With(Secure.class)
public class EatAtSeatApp extends Controller {
	public static void index() {
		User user = User.find("from User u where u.email = ?", Security.connected()).first();
		session.put("userName", user.getName());
		render(user);
	}

	public static void saveFoodCourt(FoodCourt foodcourt, File picture) {
		savePlace(foodcourt, picture);
		renderJSON(foodcourt);
	}

	public static void saveStore(Establishment store, File picture) {
		savePlace(store, picture);
		renderJSON(store);
	}

	private static void savePlace(Place place, File picture) {
		if (picture != null) {
			Picture newPicture = new Picture();
			newPicture.setMimeType(FileUtil.getExtensaoArquivo(picture));
			newPicture.setData(FileUtil.getPicture(picture));
			newPicture.save();
			place.getPictures().add(newPicture);
		}
		place.save();
	}

	public static class OrderWebSocket extends WebSocketController {
		public static void orders(long establishmentId, long beginTime, long endTime) {
			List<Order> orders = Order.find(
					"from Order o where o.establishment.id = ? and o.orderDate between ? and ?", establishmentId,
					new Date(beginTime), new Date(endTime)).fetch();
			outbound.sendJson(new Order.OrdersJsonSerializer().serialize(orders, null, null).toString());

			while (inbound.isOpen()) {
				String event = await(EventHandler.newOrderIncoming.nextEvent());
				outbound.send(event);
			}
		}
	}

	public static void sections(long id) {
		Establishment store = Establishment.findById(id);
		render(store);
	}

	public static void items(long id) {
		MenuSection section = MenuSection.findById(id);
		render(section);
	}
}
